<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 陈风任 <491085389@qq.com>
 * Date: 2020-05-07
 */

namespace app\api\model\v1;

use think\Db;
use think\Cache;
use think\Config;

/**
 * 微信小程序商城模型
 */
load_trait('controller/Jump');

class Shop extends UserBase
{
    use \traits\controller\Jump;

    private $miniproInfo = [];

    //初始化
    protected function initialize()
    {
        // 需要调用`Model`的`initialize`方法
        parent::initialize();
        $dataConf = tpSetting("OpenMinicode.conf_".self::$provider);
        $this->miniproInfo = json_decode($dataConf, true);
    }

    /**
     * 获取评价订单商品列表
     * @param $order_id
     * @param $users_id
     */
    public function getOrderComment($order_id = 0, $users_id = 0)
    {
        //判断该订单是否已经评价
        $comment_count = Db::name('shop_order_comment')->where(['order_id' => $order_id, 'users_id' => $users_id])->count();
        if (!empty($comment_count)) $this->error('该订单已经评价！');
        $order_data = model('v1.ShopOrder')->getOrderDetail($order_id, $users_id);

        return $order_data['goods'];
    }

    //添加订单评价
    public function getSaveComment($post, $users_id)
    {
        //评论是否需要审核
        $shop = getUsersConfigData('shop');
        if (isset($shop['shop_open_comment']) && $shop['shop_open_comment'] == 0){
            $this->error('未开启订单评价！');
        }
        $order_id = intval($post['order_id']);
        //判断该订单是否已经评价
        $is_comment = Db::name('shop_order')->where(['order_id' => $order_id])->value('is_comment');
        if (!empty($is_comment)) {
            $this->error('该订单已经评价！');
        }

        if (!empty($post['formData'])) {
            $post['formData'] = json_decode(htmlspecialchars_decode($post['formData']), true);
            $detail_ids = get_arr_column($post['formData'],'detail_id');
            foreach ($post['formData'] as $k => $v) {
                if (!empty($v['upload_img'])){
                    $v['upload_img'] = implode(',',$v['upload_img']);
                    $v['upload_img'] = serialize($v['upload_img']);
                }
                $v['content'] = serialize($v['content']);
                $v['add_time'] = getTime();
                $v['update_time'] = getTime();
                $v['users_id'] = $users_id;
                $v['is_anonymous'] = $post['is_anonymous'];
                $v['is_show'] = !empty($shop['shop_open_comment_audit']) ? 0 : 1;
                $v['ip_address'] = clientIP();
                unset($v['upload_img_arr']);
                unset($v['litpic']);
                unset($v['title']);
                $post['formData'][$k] = $v;
            }
            $insert_data = Db::name('shop_order_comment')->insertAll($post['formData']);
            if ($insert_data) {
                Db::name('shop_order')
                    ->where([
                        'order_id'     => $order_id,
                        'users_id'     => $users_id,
                        'order_status' => 3,
                    ])
                    ->update(['is_comment' => 1, 'update_time' => getTime()]);

                if (!empty($detail_ids)) {
                    Db::name('shop_order_details')
                        ->where('details_id', 'in', $detail_ids)
                        ->where('users_id', $users_id)
                        ->update(['is_comment' => 1, 'update_time' => getTime()]);
                }

                //评价赠送积分  start
                $score = getUsersConfigData('score');
                if (!empty($score['score_comment_status']) && !empty($score['score_comment_score'])) {
                    $score_data = [
                        'type' => 7, //看global的users_score_type_arr
                        'users_id' => $users_id,
                        'score' => $score['score_comment_score'],
                    ];
                    eyou_give_score($score_data);
                }
                //评价赠送积分 end

                \think\Cache::clear('archives');

                $this->success('评价成功！');
            }
        }
        $this->error('评价失败！');
    }

    /**
     * 获取评论列表
     */
    public function getGoodsCommentList($goods_id = 0 ,$score = 0 ,$page = 1 )
    {
        $field='a.*,u.nickname,u.head_pic';
        // 筛选条件
        $condition = [
            'a.product_id' => $goods_id,
            'a.is_show' => 1,
        ];
        $score > 0 && $condition['total_score'] = $score;

        $pagesize = empty($pagesize) ? config('paginate.list_rows') : $pagesize;
        $cacheKey = 'api-'.md5(__CLASS__.__FUNCTION__.json_encode(func_get_args()));
        $result = cache($cacheKey);
        if (true || empty($result)) {
            $paginate = array(
                'page'  => $page,
            );
            $pages = Db::name('shop_order_comment')
                ->field($field)
                ->alias('a')
                ->join('users u','a.users_id = u.users_id')
                ->where($condition)
                ->order('a.add_time desc')
                ->paginate($pagesize, false, $paginate);

            $result = $pages->toArray();

            foreach ($result['data'] as $key => $val) {
                if ($val['is_anonymous'] == 1){
                    //匿名用户
                    $val['head_pic'] = get_head_pic();
                    $val['nickname'] = '匿名用户';
                }else{
                    if (empty($val['head_pic'])){
                        $val['head_pic'] = get_head_pic();
                    }
                }
                $val['head_pic'] = get_default_pic($val['head_pic'],true);

                if (isset($val['add_time'])) {
                    $val['add_time'] = date('Y-m-d H:i:s', $val['add_time']);
                }
                if (!empty($val['upload_img'])){
                    $val['upload_img'] = unserialize($val['upload_img']);
                    $val['upload_img'] = explode(',',$val['upload_img']);
                    foreach ($val['upload_img'] as $k => $v){
                        $val['upload_img'][$k] = get_default_pic($v,true);
                    }
                }
                if (!empty($val['content'])){
                    $val['content'] = unserialize($val['content']);
                }
                $result['data'][$key] = $val;
            }
            $score_type = Db::name('shop_order_comment')
                ->where([
                    'product_id' => $goods_id,
                    'is_show' => 1,
                ])->field('count(*) as count,total_score')
                ->group('total_score')
                ->getAllWithIndex('total_score');
            $result['count']['goods'] = isset($score_type[1]) ? $score_type[1]['count'] : 0;
            $result['count']['middle'] = isset($score_type[2]) ? $score_type[2]['count'] : 0;
            $result['count']['bad'] = isset($score_type[3]) ? $score_type[3]['count'] : 0;
            $result['count']['all'] = $result['count']['goods']+$result['count']['middle']+$result['count']['bad'] ;

            cache($cacheKey, $result, null, 'getGoodsCommentList');
        }
        return $result;
    }

    // 获取我的优惠券
    public function GetMyCouponList($users_id, $type = 0)
    {
        // 筛选条件
        $filter = [];
        //0-未使用 1-已使用 2-已过期
        $filter['a.use_status'] = $type;
        // 订单数据类型
        switch ($type) {
            case '0': // 未使用
                $filter['a.end_time'] = ['>=',getTime()];
                break;
            case '1'; // 已使用
                break;
            case '2'; // 已过期
                $filter['a.end_time'] = ['<',getTime()];
                break;
        }
        $filter['a.users_id'] = $users_id;
        $filter['b.coupon_id'] = ['>',0];

        $result = Db::name('shop_coupon_use')
            ->alias('a')
            ->join('shop_coupon b','a.coupon_id = b.coupon_id','left')
            ->where($filter)
            ->order('a.add_time desc')
            ->paginate(10, false, [
                'query' => request()->param()
            ]);
        !empty($result) && $result = $result->toArray();

        foreach ($result['data'] as $k => $v ) {
            $v['coupon_form_name'] = '满减券';
            $v['start_time'] = date('Y/m/d',$v['start_time']);
            $v['end_time'] = date('Y/m/d',$v['end_time']);
            switch ($v['coupon_type']) {
                case '1': // 未使用
                    $v['coupon_type_name'] = '全部商品';
                    break;
                case '2'; // 已使用
                    $v['coupon_type_name'] = '指定商品';
                    break;
                case '3'; // 已过期
                    $v['coupon_type_name'] = '指定分类';
                    break;
            }
            $result['data'][$k] = $v;
        }

        return $result;
    }

    // 领券中心
    public function GetCouponCenter($users_id)
    {
        // 筛选条件
        $filter = [
            'status' => 1
        ];
        $filter['start_date'] = ['<=',getTime()];
        $filter['end_date'] = ['>=',getTime()];
        $coupon_type = input('param.coupon_type/d');
        if (!empty($coupon_type)) $filter['coupon_type'] = $coupon_type;

        $result = Db::name('shop_coupon')
            ->where($filter)
            ->order('sort_order asc,coupon_id desc')
            ->paginate(6, false, [
                'query' => request()->param()
            ]);
        if (!empty($result)) {
            $coupon_ids = [];
            $result = $result->toArray();
            foreach ($result['data'] as $k => $v ) {
                $coupon_ids[] = $v['coupon_id'];
                $v['coupon_form_name'] = '满减券';
                switch ($v['use_type']) {
                    case '1': // 固定期限有效
                        $v['start_date'] = date('Y/m/d',$v['start_date']);
                        $v['end_date'] = date('Y/m/d',$v['end_date']);
                        $v['use_type_name'] = $v['start_date'].'-'.$v['end_date'];
                        break;
                    case '2'; // 领取当天开始有效
                        $v['use_type_name'] = '领取'.$v['valid_days'].'天内有效';
                        break;
                    case '3'; // 领取次日开始有效
                        $v['use_type_name'] =  '领取次日开始'.$v['valid_days'].'天内有效';
                        break;
                }
                $result['data'][$k] = $v;
            }
            $have_where['users_id'] = $users_id;
            $have_where['coupon_id'] = ['in',$coupon_ids];
            $have_where['use_status'] = 0;
            $have = Db::name('shop_coupon_use')->where($have_where)->column('coupon_id');
            if (!empty($have)){
                foreach ($result['data'] as $k => $v ) {
                    if (in_array($v['coupon_id'],$have)){
                        $result['data'][$k]['geted'] = 1;//当前还有已领取未使用的
                    }
                }
            }
        }

        return $result;
    }

    // 会员余额记录
    public function getUsersMoneyDetails($users = [], $param = [])
    {
        $where = [
            'status' => ['IN', [2, 3]],
            'users_id' => $param['users_id'],
        ];
        $UsersMoney = Db::name('users_money')->where($where)->order('moneyid desc')->select();
        // 获取金额明细类型
        $pay_cause_type_arr = Config::get('global.pay_cause_type_arr');
        // 获取金额明细状态
        $pay_status_arr = Config::get('global.pay_status_arr');
        foreach ($UsersMoney as $key => $value) {
            $value['status_name'] = $pay_status_arr[$value['status']];
            $value['add_time'] = MyDate('Y-m-d H:i:s', $value['add_time']);
            $value['cause_type_name'] = $pay_cause_type_arr[$value['cause_type']];
            $UsersMoney[$key] = $value;
        }
        $users['MoneyList'] = $UsersMoney;

        // 会员余额首页
        $this->success('查询成功', null, $users);
    }

    // 会员余额充值
    public function getUsersMoneyRecharge($param = [])
    {
        // 查询充值活动数据
        $data = Db::name('users_money_recharge_type')->where('id',$param['type_id'])->find();
        if (empty($data)) $this->error('请选择充值金额');
        // 记录类型，充值
        $cause_type = 1;
        // 清理当前会员的未支付的充值记录
        $where = [
            'status' => 1,
            'cause_type' => $cause_type,
            'users_id' => $param['users_id'],
        ];
        Db::name('users_money')->where($where)->delete();

        // 查询当前会员的余额
        $where = [
            'users_id' => $param['users_id']
        ];
        $UsersMoney = Db::name('users')->where($where)->getField('users_money');

        // 充值记录数据处理
        $time = getTime();
        // 订单号规则
        $orderNumber = date('Ymd') . $time . rand(10, 100);
        // 支付类型中文名称
        $pay_cause_type_arr = Config::get('global.pay_cause_type_arr');
        // 记录数据
        $insert = [
            'users_id'      => $param['users_id'],
            'cause_type'    => $cause_type,
            'cause'         => $pay_cause_type_arr[$cause_type],
            'money'         => $data['money'],
            'actual_money'  => $data['money']+$data['give_money'],
            'users_money'   => $UsersMoney,
            'pay_method'    => 'wechat',
            'pay_details'   => '',
            'order_number'  => $orderNumber,
            'status'        => 1,
            'add_time'      => $time,
            'type_id'       => $data['id'],
            'data'          => serialize($data)
        ];
        $insertID = Db::name('users_money')->insertGetId($insert);
        if (!empty($insertID)) {
            $openid = Db::name('wx_users')->where('users_id', $param['users_id'])->getField('openid');
            $weChatPay = model('v1.ShopOrderPay')->getWechatAppletsPay($openid, $orderNumber, $data['money']);
            // $weChatPay = model('v1.ShopOrderPay')->getWechatAppletsPay($openid, $orderNumber, 0.01);
            $result = [
                'weChatPay' => $weChatPay,
                'orderData' => [
                    'moneyid' => $insertID,
                    'order_number' => $orderNumber
                ]
            ];
            $this->success('正在支付', null, $result);
        } else {
            $this->error('充值失败');
        }
    }

    // 会员余额充值后续处理
    public function getUsersMoneyRechargePay($param = [])
    {
        // 查询订单信息
        $where = [
            'cause_type' => 1,
            'users_id' => $param['users_id'],
            'moneyid' => $param['moneyid'],
            'order_number' => $param['order_number'],
        ];
        $usersMoney = Db::name('users_money')->where($where)->find();
        if (empty($usersMoney)) $this->error('订单错误，刷新重试');
        if (1 !== intval($usersMoney['status'])) $this->error('订单已被处理，刷新重试');
        $data = Db::name('users_money_recharge_type')->where('id', $usersMoney['type_id'])->find();

        // 查询会员openid
        $openid = Db::name('wx_users')->where('users_id', $param['users_id'])->getField('openid');

        // 下单确认页数据处理
        $resultData = model('v1.ShopOrderPay')->getWechatPayResult($openid, $param['order_number']);
        // 返回状态
        $returnCode = !empty($resultData['return_code']) && 'SUCCESS' == $resultData['return_code'] ? $resultData['return_code'] : '';
        $resultCode = !empty($resultData['result_code']) && 'SUCCESS' == $resultData['result_code'] ? $resultData['result_code'] : '';
        $tradeState = !empty($resultData['trade_state']) && 'SUCCESS' == $resultData['trade_state'] ? $resultData['trade_state'] : '';

        // 订单已支付，处理订单流程
        if (!empty($returnCode) && !empty($resultCode) && !empty($tradeState)) {
            // 查询当前会员的余额
            $usersWhere = [
                'users_id' => $param['users_id']
            ];
            $usersMoney = Db::name('users')->where($usersWhere)->value('users_money');

            // 充值订单已支付，将订单更新为已支付
            $update = [
                'status' => 2,
                'pay_details' => serialize($resultData),
                'update_time' => getTime(),
                'users_money' =>  floatval($usersMoney) + floatval($data['money']) + floatval($data['give_money']),
                'actual_money' => floatval($data['money']) + floatval($data['give_money'])
            ];
            $resultID = Db::name('users_money')->where($where)->update($update);
            if (!empty($resultID)) {
                // 增加会员余额
                $update = [
                    'users_money' => Db::raw('users_money+'. (floatval($data['money']) + floatval($data['give_money']))),
                    'scores' => Db::raw('scores+'. $data['give_score']),
                ];
                $resultID = Db::name('users')->where($usersWhere)->update($update);
                if (!empty($resultID)) {
                    $current_score = Db::name('users')->where($usersWhere)->value('scores');
                    // 是否有充值赠送积分
                    if (0 < $data['give_score']) {
                        $score_insert = [
                            'type' => 4,
                            'users_id' => $param['users_id'],
                            'score' => $data['give_score'],
                            'current_score' => $current_score,
                            'remark' => '充值订单:'.$param['order_number'].'赠送',
                            'add_time' => getTime(),
                            'update_time' => getTime()
                        ];
                        Db::name('users_score')->insert($score_insert);
                    }

                    // 将充值订单更新为已完成
                    $update = [
                        'status' => 3,
                        'update_time' => getTime(),
                    ];
                    Db::name('users_money')->where($where)->update($update);

                    //统计余额充值
                    eyou_statistics_data(5, floatval($data['money']));

                    // 已开启的微信订阅消息模板
                    $tmplData = Db::name('weixin_template')->where([
                            'send_scene' => ['IN', [13]],
                            'template_code'=>['gt', 0],
                            'is_open'=>1,
                        ])->order('send_scene asc')->getAllWithIndex('template_id');

                    // 返回结束
                    $this->success('支付完成', null, ['tmplData'=>$tmplData]);
                }
            }
            $this->success('订单处理失败，请联系管理员');
        }
    }

    /**************************     限时折扣 开始    ****************************/
    //获取单次显示折扣
    public function getOneDiscount($param = [])
    {
        $avtive_id = !empty($param['activeid']) ? intval($param['activeid']) : 0;

        $where['status'] = 1;
        $where['is_del'] = 0;

        //如果没传活动id就取当前正在进行的
        if (!empty($avtive_id)){
            $where['active_id'] = $avtive_id;
            $active = Db::name('discount_active')->where($where)->find();
        }else{
            $where['start_date'] = ['<=',getTime()];
            $where['end_date'] = ['>=',getTime()];
            //获取已开始未结束的限时折扣
            $active = Db::name('discount_active')->where($where)->find();
            //如果没有就取即将开始的
            if (empty($active)){
                $active = Db::name('discount_active')
                    ->where('status',1)
                    ->where('is_del',0)
                    ->where('start_date','>',getTime())
                    ->order('start_date asc')
                    ->find();
            }
        }
        $return = [];
        if (!empty($active)){
            $return['active'] = $active;

            if ($active['start_date'] <= getTime()){
                $return['active']['active_status'] = 10;//进行中
            }else{
                $return['active']['active_status'] = 20;//即将开始
            }
            $param['active_id'] = $return['active']['active_id'];
            $return['goodsList'] = $this->getDiscountGoodsList($param);
        }
        return $return;
    }

    /**
     * 限时折扣：获取限时折扣商品列表
     */
    public function getDiscountGoodsList($param = [])
    {
        $limit = !empty($param['limit']) ? intval($param['limit']) : 6;
        $active_id = $param['active_id'];
        $data = Db::name('discount_active_goods')
            ->alias('a')
            ->field('c.*,b.litpic,b.title,a.*,b.users_price')
            ->join('archives b','a.aid = b.aid')
            ->join('discount_goods c','a.discount_goods_id = c.discount_gid')
            ->where('a.active_id',$active_id)
            ->limit($limit)
            ->getAllWithIndex('aid');
        if (!empty($data)){
            $aids = [];
            foreach ($data as $k => $v){
                $data[$k]['litpic'] = get_default_pic($v['litpic'],true);
                if (1 == $v['is_sku']){
                    $aids[] = $v['aid'];
                }
            }
            //多规格
            if (!empty($aids)){
                $sku = Db::name('product_spec_value')
                    ->field('*,min(discount_price) as discount_price')
                    ->where('aid','in',$aids)
                    ->group('aid')
                    ->getAllWithIndex('aid');
            }

            foreach ($data as $k => $v){
                if (1 == $v['is_sku'] && !empty($sku[$v['aid']])){
                    $v['discount_price'] = $sku[$v['aid']]['discount_price'];
                }
                $v['progress'] = 0;
                if (0 < $v['sales_actual']){
                    $count_stock = $v['sales_actual']+$v['discount_stock']+$v['virtual_sales'];
                    $v['progress'] = intval(($v['sales_actual']+$v['virtual_sales'])/$count_stock*100);
                }else{
                    if (0 < $v['virtual_sales']){
                        $v['progress'] = intval($v['virtual_sales']/($v['virtual_sales']+$v['discount_stock'])*100);;
                    }
                }
                if (0 < $v['virtual_sales']){
                    $v['sales_actual'] = $v['sales_actual'] +$v['virtual_sales'];

                }
                $data[$k] = $v;
            }
        }
        return $data;
    }

    /**
     * 获取限时折扣列表
     */
    public function GetDiscountIndex($param = [])
    {
        $active_id = $param['active_id'];
        $page = !empty($param['page']) ? $param['page'] : 1;
        $pagesize = !empty($param['limit']) ? $param['limit'] : 20;
        $cacheKey = 'api-'.md5(__CLASS__.__FUNCTION__.json_encode(func_get_args()));
        $result = cache($cacheKey);
        if (true || empty($result)) {
            $paginate = array(
                'page'  => $page,
            );
            $pages = Db::name('discount_active_goods')
                ->alias('a')
                ->field('c.*,b.litpic,b.title,a.*,b.users_price')
                ->join('archives b','a.aid = b.aid')
                ->join('discount_goods c','a.discount_goods_id = c.discount_gid')
                ->where('a.active_id',$active_id)
                ->paginate($pagesize, false, $paginate);

            $result = $pages->toArray();

            $aids = [];
            foreach ($result['data'] as $k => $v){
                $result['data'][$k]['litpic'] = get_default_pic($v['litpic'],true);
                if (1 == $v['is_sku']){
                    $aids[] = $v['aid'];
                }
            }

            //多规格
            if (!empty($aids)) {
                $sku = Db::name('product_spec_value')
                    ->field('*,min(discount_price) as discount_price')
                    ->where('aid', 'in', $aids)
                    ->group('aid')
                    ->getAllWithIndex('aid');
            }
            //sales_actual //
            foreach ($result['data'] as $k => $v){
                if (1 == $v['is_sku'] && !empty($sku[$v['aid']])){
                    $v['discount_price'] = $sku[$v['aid']]['discount_price'];
                }
                $v['progress'] = 0;
                if (0 < $v['sales_actual']){
                    $count_stock = $v['sales_actual']+$v['discount_stock']+$v['virtual_sales'];
                    $v['progress'] = intval(($v['sales_actual']+$v['virtual_sales'])/$count_stock*100);
                }else{
                    if (0 < $v['virtual_sales']){
                        $v['progress'] = intval($v['virtual_sales']/($v['virtual_sales']+$v['discount_stock'])*100);;
                    }
                }
                if (0 < $v['virtual_sales']){
                    $v['sales_actual'] = $v['sales_actual'] + $v['virtual_sales'];

                }
                $result['data'][$k] = $v;
            }
            if(1 == $page){
                $result['active'] = $this->GetDiscount($active_id);
            }
            cache($cacheKey, $result, null, 'GetDiscountIndex');
        }

        return $result;
    }

    //获取限时折扣活动信息(不包括折扣商品信息)
    public function GetDiscount($active_id = 0)
    {
        $data = Db::name('discount_active')->where('active_id',$active_id)->find();
        if ($data['start_date'] <= getTime()){
            $data['active_status'] = 10;//进行中
        }else{
            $data['active_status'] = 20;//即将开始
        }
        return $data;
    }
    /**************************     限时折扣 结束    ****************************/

}